<script setup lang="ts">
  import { computed, PropType, ref, watch } from 'vue'
  import _ from 'lodash'
  import { useDetectResultSave } from '@/services/pages/return-factory/useReturnFactory'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { ElTable, ElTableColumn, ElInput } from 'element-plus'
  import videoCover from '@/assets/image/pages/order/new/video.png'
  import VideoPreview from '@/components/pages/return-factory/index/create/custom-info/VideoPreview.vue'

  const { saveParam, saveLoading, save } = useDetectResultSave()

  defineOptions({
    name: 'DetectionResultFillModalDetectionDetail',
  })

  interface GoodList extends ReturnFactoryDetectGood {
    recommend: string
    measure: string
  }

  const props = defineProps({
    goodList: {
      type: Array as PropType<Array<ReturnFactoryDetectGood>>,
      required: true,
    },
    detectId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 视频预览链接列表
  const videoPreviewUrls = ref<Array<string>>([])

  // 预览视频索引
  const videoPreviewIndex = ref(0)

  // 预览视频弹窗显示状态
  const videoPreviewModalVisible = ref(false)

  // 填写检测报告抽屉显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 设备列表
  const _goodList = ref<Array<GoodList>>([])

  /**
   * 隐藏抽屉事件
   */
  const hideDrawer = () => {
    _goodList.value.length = 0
    visible.value = false
  }

  /**
   * 确定事件
   */
  const onConfirm = async () => {
    saveParam.value = _goodList.value.map((item) => {
      return {
        checkResult: item.checkResult,
        id: item.id,
        measure: item.measure,
        recommend: item.recommend,
        repairGoodsId: item.repairGoodsId,
      }
    })
    const res = await save(props.detectId)
    if (res.code === 20000) {
      HMessage.success('填写检测结果成功')
      hideDrawer()
      emits('update')
      return
    }

    HMessageBox.error(res.message)
  }

  // 表格图片列的列宽
  const tablePictureColumnWidth = computed(() => {
    const max = Math.max(..._goodList.value.map((good) => good.repairGoodsImages.length))
    return (max || 1) * 75
  })

  // 表格视频列的列宽
  const tableVideoColumnWidth = computed(() => {
    const max = Math.max(..._goodList.value.map((good) => good.repairGoodsVideos.length))
    return (max || 1) * 75
  })

  /**
   * 视频预览事件
   * @param {Number} index - 设备索引
   */
  const handlePreviewVideo = (index: number) => {
    videoPreviewUrls.value = _goodList.value[index].repairGoodsVideos
    videoPreviewIndex.value = index
    videoPreviewModalVisible.value = true
  }

  watch(
    visible,
    (value) => {
      if (value) {
        _goodList.value = _.cloneDeep(
          props.goodList.map((item) => {
            return Object.assign(item, { recommend: '', measure: '' })
          }),
        )
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    title="填写检测报告"
    :width="1200"
    unit="px"
    :loading="saveLoading"
    @close="hideDrawer"
  >
    <el-table stripe :border="true" :data="_goodList">
      <!--序号-->
      <el-table-column type="index" fixed="left" :align="'center'" width="50" label="序号" />

      <!--序列号-->
      <el-table-column label="序列号" prop="snCode" width="100" show-overflow-tooltip />

      <!--设备类型-->
      <el-table-column label="设备类型" prop="goodsModel" width="100" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.type === 1 ? '成品' : '配件' }}
        </template>
      </el-table-column>

      <!--设备编号-->
      <el-table-column label="设备编号" prop="goodsCode" width="100" show-overflow-tooltip />

      <!--设备型号-->
      <el-table-column label="设备型号" prop="goodsModel" width="100" show-overflow-tooltip />

      <!--设备规格-->
      <el-table-column label="设备规格" prop="goodsSpecName" width="100" show-overflow-tooltip />

      <!--质保开始-->
      <el-table-column label="质保开始" prop="warrantyStartTime" width="140" />

      <!--质保结束-->
      <el-table-column label="质保结束" prop="warrantyEndTime" width="140" />

      <!-- 返厂描述 -->
      <el-table-column label="返厂描述" width="160" prop="descr" show-overflow-tooltip />

      <!-- 返厂图片 -->
      <el-table-column label="返厂图片" :width="tablePictureColumnWidth">
        <template #default="{ row }">
          <div class="image-list">
            <h-image
              v-for="(img, index) in row.repairGoodsImages"
              :key="index"
              :show-del-btn="false"
              :src="img"
              :preview-src-list="row.images"
              :padding="2"
              :width="60"
              :height="37.5"
              :initial-index="index"
            />
          </div>
        </template>
      </el-table-column>

      <!-- 返厂视频 -->
      <el-table-column label="返厂视频" :width="tableVideoColumnWidth">
        <template #default="{ row }">
          <div class="image-list">
            <h-image
              v-for="(video, index) in row.repairGoodsVideos"
              :key="index"
              :show-del-btn="false"
              :is-show-img-preview="false"
              :src="videoCover"
              :padding="2"
              :width="60"
              :height="37.5"
              :initial-index="index"
              @preview="handlePreviewVideo(index)"
            />
          </div>
        </template>
      </el-table-column>

      <!--检测结果-->
      <el-table-column label="检测结果" width="360">
        <template #default="{ row }">
          <el-input
            v-model.trim="row.checkResult"
            placeholder="请输入检测结果"
            maxlength="500"
            type="textarea"
            show-word-limit
            resize="both"
          />
        </template>
      </el-table-column>

      <!--解决措施-->
      <el-table-column label="解决措施" width="360">
        <template #default="{ row }">
          <el-input
            v-model.trim="row.measure"
            placeholder="请输入解决措施"
            maxlength="500"
            type="textarea"
            show-word-limit
            resize="both"
          />
        </template>
      </el-table-column>

      <!--解决建议-->
      <el-table-column label="解决建议" width="360">
        <template #default="{ row }">
          <el-input
            v-model.trim="row.recommend"
            placeholder="请输入解决建议"
            maxlength="500"
            type="textarea"
            show-word-limit
            resize="both"
          />
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="hideDrawer">取消</h-button>
    </template>

    <video-preview
      v-model:visible="videoPreviewModalVisible"
      :video-list="videoPreviewUrls"
      :initial-index="videoPreviewIndex"
    ></video-preview>
  </h-drawer>
</template>

<style scoped lang="scss">
  :deep(.el-textarea__inner) {
    width: 335px !important;
    min-height: 28px !important;
    height: 28px;
    max-height: 370px;
  }

  .image-list {
    display: flex;
    column-gap: 5px;
  }
</style>
